package edu.cmu.km.kernel.tree.xml;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

/**
 * Encapsulate a Node in XML Node. This will be used to initialize Tree Node as
 * data type T provide toString method for print.
 * 
 * @author WhiteMaeda
 * 
 * @param <T>
 */
public class XMLNodeData {

	private org.w3c.dom.Node xmlNode;

	public XMLNodeData(org.w3c.dom.Node xmlNode) {
		this.xmlNode = xmlNode;
	}

	/**
	 * Give specification how two nodes are equal. This method internally decide
	 * whether two xml nodes are equal dependent on their type
	 * 
	 * @param data
	 * @return
	 */
	public boolean equals(XMLNodeData data) {
		if (this.xmlNode.getNodeType() == data.xmlNode.getNodeType()) {
			switch (this.xmlNode.getNodeType()) {
			case Node.TEXT_NODE:
				if (this.xmlNode.getNodeValue() == data.xmlNode.getNodeValue())
					return true;
				else
					return false;
			case Node.ELEMENT_NODE:
				if (this.xmlNode.getNodeName() == data.xmlNode.getNodeName()) {
					NamedNodeMap this_attributes = this.xmlNode.getAttributes();
					NamedNodeMap data_attributes = data.xmlNode.getAttributes();
					if (this_attributes.getLength() == data_attributes
							.getLength()) {
						int i =0;
						for (i = 0; i < this_attributes.getLength(); i++) {
							Node current1 = this_attributes.item(i);
							Node current2 =  data_attributes.item(i);
							if(current1.getNodeName()==current2.getNodeName()&&
									current1.getNodeValue()==current2.getNodeValue())
								continue;
						}
						if(i>0 && i == this_attributes.getLength()) return true;
					}
				}
				return false;
			case Node.DOCUMENT_NODE:
				return true;				
			case Node.COMMENT_NODE:
				return true;
			case Node.NOTATION_NODE:
				return true;
			}

		}
		return false;
	}

	/**
	 * provide method to print XML node information
	 */
	public String toString() {
		String s = "";
		org.w3c.dom.Node node = xmlNode;
		switch (node.getNodeType()) {

		case org.w3c.dom.Node.DOCUMENT_NODE:
			s = "<xml version=\"1.0\">";
			break;

		case org.w3c.dom.Node.ELEMENT_NODE:
			String name = node.getNodeName();
			s = "<" + name;
			NamedNodeMap attributes = node.getAttributes();
			for (int i = 0; i < attributes.getLength(); i++) {
				org.w3c.dom.Node current = attributes.item(i);
				s += (" " + current.getNodeName() + "=\""
						+ current.getNodeValue() + "\"");
			}
			s += ("/>");
			// s += ("</" + name + ">");
			break;

		case org.w3c.dom.Node.TEXT_NODE:
			s = node.getNodeValue();
			break;
		}
		return s;
	}

}
